package com.youkeyi.ddy.cloud.common.wx.applet.message.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.youkeyi.ddy.cloud.common.constant.YoukeyiDdyApplicationSystemConstant;
import com.youkeyi.ddy.cloud.common.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * WxToken
 *
 * @Author liuxiawang
 * @Date 5/4/23 5:41 PM
 * @Location shenzhen.china
 */
public class WxTokenUtils {

    public static final String APPLET_APPID_DDY = "wx0411fb6a82e1551d";

    private static Map<String, String> appidSceretMap = new HashMap<>();
    static {
        appidSceretMap.put("wx5589a0e69a84dbef", "844c5fd085b5fb35641405a790bf94f7"); // DDY 公众号
        appidSceretMap.put("wx0411fb6a82e1551d", "832bff3fb574a945026e564555310f35"); // DDY 小程序
    }

    public static String getAccessToken() {
        return getAccessToken(APPLET_APPID_DDY);
    }

    public static String getAccessToken(String appId) {
        if (StringUtils.isBlank(appId)) {
            appId = APPLET_APPID_DDY;
        }
        String appIdSecret = appidSceretMap.get(appId);
        if (StringUtils.isBlank(appIdSecret)) {
            return null;
        }
        String redisKey = appId + "_AccessToken";
        String accessToken = null;
        try {
            accessToken = RedisUtils.getStringFromJedis(YoukeyiDdyApplicationSystemConstant.AUTH_REDIS_DB_INDEX, redisKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }

        String urlGetToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId +"&secret=" + appIdSecret;
        String res = HttpUtil.get(urlGetToken);
        JSONObject jsonObject = JSONObject.parseObject(res);
        accessToken = jsonObject.getString("access_token");
        try {
            RedisUtils.addStringToJedis(YoukeyiDdyApplicationSystemConstant.AUTH_REDIS_DB_INDEX, redisKey, accessToken, 6998);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }
}
